package com.dys.ai.config;

import com.alibaba.nacos.common.packagescan.util.NestedExceptionUtils;
import com.dys.ai.enumeration.BookingStatus;
import com.dys.ai.service.FlightBookingService;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;

import java.time.LocalDate;
import java.util.function.Function;

/**
 * AI调用服务
 */
@Slf4j
@Configuration
public class BookingTools {

    private final FlightBookingService flightBookingService;

    public BookingTools(FlightBookingService flightBookingService) {
        this.flightBookingService = flightBookingService;
    }

    /**
     * 注意：状态存的是0,1,2 需要转换成中文或者枚举都可以
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public record BookingDetails(String bookingNumber, String name, LocalDate date, BookingStatus bookingStatus,
                                 String from, String to, String bookingClass) {
    }

    public record CancelBookingRequest(String bookingNumber, String name) {}

    /**
     * Description 告诉大模型：什么对话才回调
     * @return 退订
     */
    @Bean
    @Description("处理机票退订")
    public Function<CancelBookingRequest,String> cancelBooking(){
        return cancelBookingRequest->{
            // apply调用退订方法
            flightBookingService.cancelBooking(cancelBookingRequest.bookingNumber, cancelBookingRequest.name);
            return "退订成功!";
        };
    }

    /**
     * 预定信息
     * @param bookingNumber 预定编号
     * @param name 预定姓名
     */
    public record BookingDetailsRequest(String bookingNumber, String name) {
    }

    /**
     * 获取机票预定详情
     * @return 机票预定详情
     */
    @Bean
    @Description("获取机票预订详细信息")
    public Function<BookingDetailsRequest, BookingDetails> getBookingDetails() {
        return request -> {
            try {
                return flightBookingService.getBookingDetails(request.bookingNumber(), request.name());
            }
            catch (Exception e) {
                log.warn("Booking details: {}", NestedExceptionUtils.getMostSpecificCause(e).getMessage());
                return new BookingDetails(request.bookingNumber(), request.name(), null, null, null, null, null);
            }
        };
    }

    /**
     * 修改预订
     * @param bookingNumber 预定编号
     * @param name 姓名
     * @param date 出发日期
     * @param from 出发地
     * @param to 目的地
     */
    public record ChangeBookingDatesRequest(String bookingNumber, String name, String date, String from, String to) {
    }

    @Bean
    @Description("修改机票预订信息")
    public Function<ChangeBookingDatesRequest, String> changeBooking() {
        return request -> {
            flightBookingService.changeBooking(request.bookingNumber(), request.name(), request.date(), request.from(),
                    request.to());
            return "修改预订信息成功";
        };
    }
}
